layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func',], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;

    /**
     * 系统管理--消息管理
     */
    var Notice = {
        tableId: "noticeTable"    //表格id
    };

    //监听单元格编辑
    table.on('edit(noticeTable)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        $.ajax({
            type: "PUT",
            url: "/gcgWsjdTakeaway/update",
            datatype: "json",
            data: data,
            success: function (data) {
                table.reload(Notice.tableId);
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
            }

        });
    });

    /**
     * 初始化表格的列
     */
    Notice.initColumn = function () {
        return [[
            {type: 'checkbox', fixed: 'left'},
            {align: 'center', type: "numbers", title: '序号', fixed: 'left'},
            {field: 'gcgWsjdId', align: "center", hide: true, title: 'id'},
            // {field: 'yaoma', align: "center", sort: false, title: '妖码'},
            {
                field: 'mingcheng',
                align: "center",
                sort: false,
                title: '外卖店名',
                minWidth: 180,
                fixed: 'left',
                edit: 'text',
                templet: function (d) {
                    // return '<div><span>'+d.mingcheng+'</span></br><span style="color: #999">妖码：'+d.yaoma+'</span></div>';
                    let meituan = '';
                    let eleme = '';
                    if (d.tm != "" && d.tm != undefined) {
                        meituan = "<span style='background-color: #FFB800; color: red; padding: 0px 5px'></span>";
                    }
                    if (d.te != "" && d.te != undefined) {
                        eleme = "<span style='background-color: #1E9FFF; color: #FFF; padding: 0px 5px'></span>";
                    }
                    return `
                        <div style="height: 28px">${d.mingcheng}</div>
                        <input class="gcgWsjdId" value="${d.gcgWsjdId}" hidden >
                        <input class="shStatus" value="${d.shStatus}" hidden >
                        <div>
                            <span style="color: #999;margin-right: 5px">妖码: <em style="font-style: normal;">${d.yaoma}</em></span>
                            ${meituan}&nbsp; ${eleme}
                        </div>
                    `
                    // return '<div>'+d.mingcheng+'</div>' + d.tm.length > 1 ? '<span><sss></sss></span>' : '' + '<span style="color: #999">妖码：</span><span style="color: #999">'+d.yaoma+'</span>';
                }
            },
            {field: 'wsjdDm', align: "center", sort: false, title: '原店名', minWidth: 80},
            {field: 'dizhiXiangxi', align: "center", sort: false, title: '门店地址', minWidth: 80},
            {field: 'mdTel', align: "center", sort: false, title: '<div style="transform: scale(.8)">门店（前厅/客服）<br>电话订餐电话</div>', minWidth: 100},
            {field: 'lxrName', align: "center", sort: false, title: '联系人', minWidth: 50},
            {field: 'lxrTel', align: "center", sort: false, title: '电话', minWidth: 90},
            {field: 'jsTel', align: "center", sort: false, title: '<div style="transform: scale(.8)">门店账密<br>手机号码</div>'},
            {field: 'mdYysj', align: "center", sort: false, title: '营业时间', minWidth: 80},
            {field: 'yhkName', align: "center", sort: false, title: '开户人', minWidth: 80},
            {field: 'yhkHao', align: "center", sort: false, title: '银行卡', minWidth: 80},
            {field: 'isFapiao', align: "center", sort: false, title: '开发票', minWidth: 60},
            {field: 'isYouhui', align: "center", sort: false, title: '申请优惠', minWidth: 60},
            {
                field: 'farenSfzPic', align: "center", sort: false,
                title: '<div>法人身份信息</div> ' +
                    '<div><span class="cadr">正面</span><span class="cadr">反面</span><span class="cadr">手持</span></div>',
                minWidth: 200, templet: function (d) {
                    return '<div><span class="cadr1"><img src="' + d.farenSfzPic1 + '" onclick=\'imgViewer(this)\' ></span>' +
                        '<span class="cadr1"><img src="' + d.farenSfzPic2 + '" onclick=\'imgViewer(this)\'  class="img"></span>' +
                        '<span class="cadr1"><img src="' + d.farenSfzPic3 + '" onclick=\'imgViewer(this)\' class="img"></span></div>'
                }
            },
            {
                field: 'dzSfzPic1',
                align: "center",
                sort: false,
                title: '<div>店长身份信息</div> ' +
                    '<div><span class="cadr">正面</span><span class="cadr">反面</span><span class="cadr">手持</span></div>',
                minWidth: 150, templet: function (d) {
                    return '<div><span class="cadr1"><img src="' + d.dzSfzPic1 + '" onclick=\'imgViewer(this)\' ></span>' +
                        '<span class="cadr1"><img src="' + d.dzSfzPic2 + '" onclick=\'imgViewer(this)\' class="img"></span>' +
                        '<span class="cadr1"><img src="' + d.dzSfzPic3 + '" onclick=\'imgViewer(this)\' class="img"></span></div>'
                }
            },
            {
                field: 'yingyeZhizhao',
                align: "center",
                sort: false,
                title: '营业执照',
                minWidth: 90,
                templet: function (d) {
                    if (d.yingyeZhizhao === undefined || d.yingyeZhizhao === "") {
                        return "<p>暂无</p>";
                    } else {
                        return "<img src='" + d.yingyeZhizhao + "' style='max-width: 100%;' onclick='imgViewer(this)' class='img'>";
                    }
                }
            },
            {
                field: 'shipinXkz',
                align: "center",
                sort: false,
                title: '<div style="transform: scale(.8)">食品经营<br>许可证</div>',
                minWidth: 130,
                templet: function (d) {
                    if (d.shipinXkz === undefined || d.shipinXkz === "") {
                        return "<p>暂无</p>";
                    } else {
                        return "<img src='" + d.shipinXkz + "' style='max-width: 100%;' onclick='imgViewer(this)' class='img'>";
                    }
                }
            },
            // {
            //     field: 'sbShouquan',
            //     align: "center",
            //     sort: false,
            //     title: '授权书',
            //     minWidth: 90,
            //     templet: function (d) {
            //         if (d.sbShouquan === undefined || d.sbShouquan === "") {
            //             return "<p>暂无</p>";
            //         } else {
            //             return "<img src='" + d.sbShouquan + "' style='max-width: 100%;' onclick='imgViewer(this)' class='img'>";
            //         }
            //     }
            // },
            {field: 'createTime', align: "center", sort: false, title: '申请时间', minWidth: 100},
            {field: 'shenpiShijian', align: "center", sort: false, title: '通过(驳回)时间', minWidth: 130},
            {
                field: 'shStatus', align: "center", sort: false, title: '审核状态', minWidth: 100, templet: function (d) {
                    if (d.shStatus == '1') {
                        return "待审核";
                    } else if (d.shStatus == '2') {
                        return "已驳回";
                    } else if (d.shStatus == '3') {
                        return "已通过";
                    }
                }
            },
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 120}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Notice.search = function () {
        var queryData = {};
        queryData['shStatus'] = $("#shStatus").val();
        queryData['yaoma'] = $("#yaoma").val();
        queryData['mingcheng'] = $("#mingcheng").val();
        table.reload(Notice.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 点击清空按钮
     */
    Notice.reset = function () {
        $('input').val('');
        $('#ad').val('');
        $('#mingcheng').val('');
        $('#shStatus').val('');
        form.render();
        $(function () {
            var queryData = {};
            queryData['shStatus'] = $("#shStatus").val();
            table.reload(Notice.tableId, {
                where: queryData, page: {curr: 1}
            });
        })
    };

    // 点击空白处关闭展开全部弹窗
    $(document).on('click', function(event) {
        var tableTips = $('.layui-layer.layui-layer-tips.layui-table-tips');
        if(tableTips.length) {
            var tagElem = event.target || event.srcElement;
            if(tableTips.find(tagElem).length) {
                layui.stope(event);
            } else {
                layui.layer.close(tableTips.attr('times'));
            }
        }
    });

    /**
     * 导出excel按钮
     */
    Notice.btnImport = function (data) {
        //获取导出Excel的数据
        var url = Feng.ctxPath + "/gcgWsjdTakeaway/listExport?taStatus=" + data;
        location.href = url;
    };

    form.on('select(startWorkYn)', function (data) {
        Notice.search();
    });

    /**
     * 确认完成按钮
     */
    Notice.doneSome = function (type) {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择已完成的门店");
        } else {
            for (var i in data) {
                ids += data[i].gcgWsjdId + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/gcgWsjdTakeaway/doneSome", function (result) {
                    if(result.success){
                        Feng.success("确认成功!");
                        table.reload(Notice.tableId);
                    }else {
                        Feng.error("确认失败!" + result.message + "!");
                    }

                }, function (result) {
                    Feng.error("确认失败!" + result.message + "!");
                });
                ajax.set("ids", ids);
                ajax.set("taStatus", type);
                ajax.start();
            };
            Feng.confirm("是否批量完成?", operation);
        }
    };

    /**
     * 批量下载按钮
     */
    Notice.btnDown = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要批量下载的店面");
        } else {
            for (var i in data) {
                ids += data[i].gcgWsjdId + ",";
            }
            var operation = function () {
                var loding = layer.load('正在下载...',1, { shade: [0.5,'#000'] });
                parent.layer.closeAll();
              setTimeout(()=>{
                  var ajax = new $ax(Feng.ctxPath + "/gcgWsjdTakeaway/btnDown", function () {
                      Feng.success("下载成功!");
                      layer.close(loding);
                      table.reload(Notice.tableId);
                  }, function (result) {
                      Feng.error("下载失败!" + result.responseJSON.message + "!");
                  });
                  ajax.set("ids", ids);
                  ajax.start();
              },100)
            };
            Feng.confirm("是否批量下载?", operation);
        }
    };

    /**
     * 批量通过按钮
     */
    Notice.btnPass = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择通过审核的门店");
        } else {
            for (var i in data) {
                ids += data[i].gcgWsjdId + ",";
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/gcgWsjdTakeaway/updatePassMany", function () {
                    Feng.success("已通过!");
                    table.reload(Notice.tableId);
                }, function (result) {
                    Feng.error("审核失败!" + result.responseJSON.message + "!");
                });
                ajax.set("id", ids);
                ajax.start();
            };
            Feng.confirm("是否批量通过?", operation);
        }
    };

    /**
     * 通过
     *
     * @param data 点击按钮时候的行数据
     */
    var _delay = false;
    Notice.pass = function (data) {
        var operation = function () {
            if (_delay) {
                return;
            }
            ;
            _delay = true;
            setTimeout(() => {
                _delay = false
            }, 2000);
            var ajax = new $ax(Feng.ctxPath + "/gcgWsjdTakeaway/pass", function (data) {
                Feng.success("已通过!");
                table.reload(Notice.tableId);
            }, function (data) {
                Feng.error("出现错误!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.gcgWsjdId);
            ajax.start();
        };
        Feng.confirm("是否通过?", operation);
    };

    /**
     * 驳回
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.rebut = function (data) {
        func.open({
            title: '驳回外卖信息',
            content: Feng.ctxPath + '/gcgWsjdTakeaway/rebut?gcgWsjdId=' + data.gcgWsjdId,
            tableId: Notice.tableId
        });
    };
    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Notice.tableId,
        url: Feng.ctxPath + '/gcgWsjdTakeaway/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: Notice.initColumn(),
        where: {shStatus: $('#shStatus').val()},
        done: function (res) {
            $('.title-tr').remove()
            if (res.data == '') {
                $('.layui-table-box').css('overflow', 'auto')
                $('.layui-table-header, .layui-table-body').css('overflow', 'visible')
            }
            // $('.layui-table thead tr').before('<tr class="title-tr"><td colspan="2"></td><th colspan="8" style="text-align: center;"><span class="jb">基本信息</span></th><th colspan="4" style="text-align: center;">金融信息</th><th colspan="5" style="text-align: center;">证件信息</th><th colspan="6" class="th"></th></tr>')
            $('.layui-table thead tr').before('<tr class="title-tr"><td colspan="2"></td><th colspan="8" style="text-align: center;"><span class="jb">基本信息</span></th><th colspan="4" style="text-align: center;">金融信息</th><th colspan="4" style="text-align: center;">证件信息</th><th colspan="5" class="th"></th></tr>')
        }
    });
    var tempView = null
    imgViewer = function (img) {
        let _tr = $(img).parents('tr');
        let index = $(_tr).index();
        tempView = $('.layui-table-main tbody tr[data-index= ' + index + ']')
        tempView.viewer()
        $('.rebut').css('display', 'block');
        let _id = $('.layui-table-main tbody tr[data-index= ' + index + '] .gcgWsjdId').val();
        let _shStatus = $('.layui-table-main tbody tr[data-index= ' + index + '] .shStatus').val();
        if(_shStatus == 1 && $("#ad").val() == "2"){
            setTimeout(() => {
                $('.viewer-container').append(`
                <input id="gcgWsjdId" type="hidden" name="shopId" value="${_id}">
                <input id="gcgWsjdIndex" type="hidden"  value="${index}">
                <div class="rebut">
                            <div class="layui-form-item">
                                <div class="layui-input-block" style="margin-bottom: 31px;">
                                    <input class="rebutReason" type="hidden" name="shopId" value="301">
                                     <div class="rebut_name">法人身份信息驳回原因</div>
                                    <input type="text" name="title"  placeholder="请输入驳回原因" autocomplete="off" class="layui-input" id="frReason">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-input-block" style="margin-bottom: 31px;">
                                    <input class="rebutReason" type="hidden" name="shopId" value="302">
                                    <div class="rebut_name">店长身份信息驳回原因</div>
                                    <input type="text" name="title" placeholder="请输入驳回原因" autocomplete="off" class="layui-input" id="dzReason">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-input-block" style="margin-bottom: 31px;">
                                    <input class="rebutReason" type="hidden" name="shopId" value="31">
                                     <div class="rebut_name">营业执照驳回原因</div>
                                    <input type="text" name="title" placeholder="请输入驳回原因" autocomplete="off" class="layui-input" id="yyReason">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block" style="margin-bottom: 31px;">
                                    <input class="rebutReason" type="hidden" name="shopId" value="32">
                                      <div class="rebut_name">食品经营许可证驳回原因</div>
                                    <input type="text" name="title" placeholder="请输入驳回原因" autocomplete="off" class="layui-input" id="spReason">
                                </div>
                            </div>
<!--                            <div class="layui-form-item">-->
<!--                                <div class="layui-input-block" style="margin-bottom: 31px;">-->
<!--                                    <input class="rebutReason" type="hidden" name="shopId" value="303">-->
<!--                                      <div class="rebut_name">授权书驳回原因</div>-->
<!--                                    <input type="text" name="title" placeholder="请输入驳回原因" autocomplete="off" class="layui-input" id="sqReason">-->
<!--                                </div>-->
<!--                            </div>-->
                            <div class="layui-form-item">
                                <div class="layui-input-block" style="text-align: center">
                                    <button class="layui-btn" lay-submit lay-filter="formDemo" id="goBack" data-id="${_id}">驳回</button>
                                </div>
                            </div>
                        </div>
                `)
            }, 300);
        }

        return
    };


    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Notice.search();
    });

    // 清空按钮点击事件
    $('#reset').click(function () {
        Notice.reset();
    });

    // 驳回图片按钮点击事件
    $(document).on('click', '#goBack', function () {
        let id = $(this).attr('data-id')
        Notice.rebutP(id);
    });
    /**
     * 驳回图片
     *
     * @param data 点击按钮时候的行数据
     */

    Notice.rebutP = function (id) {
        let  data = [];
        let filled = false;
        $('.viewer-container input.rebutReason').each(function (index, e) {
            var obj = {};
            obj.gcgWsjdShenpixiangId= $(this).val();
            obj.miaoshu = $(this).next().next().val();
            if(obj.miaoshu != null && obj.miaoshu != ""){
                data.push(obj);
                filled = true
            }
        });
        if (!filled){
            Feng.error("至少填写一项驳回意见！");
            return
        }

        var ajax = new $ax(Feng.ctxPath + "/gcgWsjdTakeaway/rebutL", function (data) {
            Feng.success("驳回成功！");
            setTimeout(()=>{
                table.reload(Notice.tableId);
            },100)
            tempView.viewer('destroy')
            let index = $('#gcgWsjdIndex').val()
            $('.layui-table-main tbody tr[data-index= ' + index + '] .shStatus').val(2);
        }, function (res) {
            Feng.error("驳回失败！" + res.responseJSON.message);
        });
        // ajax.set("id", $("#gcgWsjdId").val());
        ajax.set("id", id);
        ajax.set("data", JSON.stringify(data));
        ajax.start();
    };

    // 完成确认美团点击事件
    $('#btnDoneM').click(function () {
        Notice.doneSome(1);
    });

    // 完成确认饿了么点击事件
    $('#btnDoneE').click(function () {
        Notice.doneSome(2);
    });

    // 导出美团点击事件
    $('#btnImportM').click(function () {
        Notice.btnImport(1);
    });

    // 导出饿了么点击事件
    $('#btnImportE').click(function () {
        Notice.btnImport(2);
    });

    // 批量下载点击事件
    $('#btnDown').click(function () {
        Notice.btnDown();

    });

    // 批量通过
    $('#btnPass').click(function () {
        Notice.btnPass();

    });

    //工具条点击事件
    table.on('tool(' + Notice.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'pass') {
            Notice.pass(data);
        } else if (layEvent === 'rebut') {
            Notice.rebut(data);
        }
    });

});
